package com.abc.http.example.high.token;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description: Token 实现
 * @author: yansl.cn
 * @create: 2023-01-18 09:40
 */
@Component
public class TokenHandler {

    /**
     * 缓存Token
     */
    private static Token token;

    /**
     * 锁机制
     */
    private Object object = new Object();

    @Value("${appId}")
    private String appId;
    @Value("${secretKey}")
    private String secretKey;

    @Autowired
    private TokenAPI tokenAPI;

    /**
     * 获取Token数据
     * 
     * @return
     */
    public String getToken() {
        if (Objects.nonNull(token) && token.timeOutBool()) {
            return token.getToken();
        }
        synchronized (object) {
            if (Objects.nonNull(token) && token.timeOutBool()) {
                return token.getToken();
            }
            // 重新获取Token
            remoteToken();
        }
        return token.getToken();
    }

    private void remoteToken() {
        // GET模式
        /* token = tokenAPI.getTokenV1(appId, secretKey);
        */

        // POST模式
        TokenParam tokenParam = new TokenParam();
        tokenParam.setAppId(appId);
        tokenParam.setSecret(secretKey);

        token = tokenAPI.getTokenV2(tokenParam);

        token.init();
    }
}
